<?php
declare (strict_types = 1);
namespace app\api\controller\union;

use app\LoginController;
use app\model\MyException;
use app\model\table\config\ConfigGlobal;
use app\model\table\talk\Talk;
use app\model\table\union\Union;
use app\model\table\user\User;
use app\model\tablenot\tool\Tool;
use think\facade\Db;
use hg\apidoc\annotation as Apidoc;


/**
 * @Apidoc\Title("工会")
 */
class UnionController extends LoginController
{
    /**
     * @Apidoc\Title("工会-分页")
     * @Apidoc\Method("GET")
     * @Apidoc\Param ("page",require=true, type="int", desc="第几页")
     * @Apidoc\Param ("pagesize",require=true, type="int", desc="一页多少条")
     * @Apidoc\Param ("name",require=true, type="int", desc="企业名字，支持模糊搜索,不需要这个条件的时候不要传这个参数")
     * @Apidoc\Returned("user_id", type="int", desc="工会创建人用户id")
     * @Apidoc\Returned("UserInfo.name", type="int", desc="工会创建人")
     * @Apidoc\Returned("name", type="int", desc="工会名称")
     * @Apidoc\Returned("icon", type="int", desc="工会标志log")
     * @Apidoc\Returned("desc", type="int", desc="工会描述")
     * @Apidoc\Returned("join_level", type="int", desc="工会加入等级")
     * @Apidoc\Returned("member_max", type="int", desc="工会最大工会成员数量")
     * @Apidoc\Returned("member_now", type="int", desc="当前工会成员数量")
     * @Apidoc\Returned("help_num", type="int", desc="帮助别人次数")
     * @Apidoc\Returned("created_at", type="int", desc="工会创建时间")
     */
    public function pageAction()
    {
        Tool::checkParam(['page','pagesize'], $this->get);
        $where['pagesize'] = $this->get['pagesize'];
        $where['orderBy'] = "created_at desc";
        if(isset($this->get['name'])){
            $where[] = ['name','like', "%".$this->get['name']."%"];
        }
        $objs = Union::instance()->page($where);
        $JoinWith=['UserInfo'];
        Union::instance()->dealJoinWith($objs['data'],$JoinWith);
        $this->setData($objs);
        $this->sendJson();
    }


    /**
     * @Apidoc\Title("工会-新增")
     * @Apidoc\Desc ("1.一个用户只能创建一个工会。2.创建工会必须没有加入任何工会。3. 金币不足不能创建工会")
     * @Apidoc\Method("POST")
     * @Apidoc\Param ("name",require=true, type="String", desc="名称")
     * @Apidoc\Param ("icon",require=true, type="String", desc="icon，50个字符以内，对应APP资源地址")
     * @Apidoc\Param ("desc",require=true, type="String", desc="描述200个字以内")
     * @Apidoc\Param ("joinLevel",require=true, type="int", desc="加入等级，数字0到9999，例如填10，用户等级10可以加入，9及不能加入")
     */
    public function addAction()
    {
        try {
            Tool::checkParam(['name','icon','desc','joinLevel'], $this->post);
            $userId = $this->user['id'];
            $name = $this->post['name'];
            $icon = $this->post['icon'];
            $desc = $this->post['desc'];
            $joinLevel = $this->post['joinLevel'];
            // 创建工会必须没有加入任何工会
            if($this->user['union_id'] != 0){
                throw new MyException("请退出工会后再操作");
            }
            // 获取创建工会需要的金币
            $union_cerate_money = ConfigGlobal::instance()->findValue("union_cerate_money");
            if($this->user['gold'] < $union_cerate_money){
                //throw new MyException("金币不足");
            }
            // 获取配置的工会最大人数
            $union_member_max = ConfigGlobal::instance()->findValue("union_member_max");

            // 获取用户
            $postData = array(
                'user_id' => $userId,
                'name' => $name,
                'icon' => $icon,
                'desc' => $desc,
                'join_level' => $joinLevel,
                'member_max' => $union_member_max,
                'member_now' => 1,
                'created_at' => $this->time,
            );
            // 启动事务
            Db::startTrans();
            // 创建工会
            $UnionObj = Union::instance()->addOne($postData);
            // 扣除用户金币
            $gold = $this->user['gold'] - $union_cerate_money;
            $userPostData = array(
                'id' => $userId,
                'gold' => $gold,
                'union_id' => $UnionObj['id']
            );
            User::instance()->updateOne($userPostData);
            Db::commit();
            $this->sendJson();
        } catch (MyException $e) {
            echo $e->toJson();
        }
    }

    /**
     * @Apidoc\Title("工会-修改")
     * @Apidoc\Desc ("1.只有创建工会的人可以修改工会信息，工会名称不能改变")
     * @Apidoc\Method("POST")
     * @Apidoc\Param ("icon",require=true, type="String", desc="icon，50个字符以内，对应APP资源地址")
     * @Apidoc\Param ("desc",require=true, type="String", desc="描述200个字以内")
     * @Apidoc\Param ("joinLevel",require=true, type="int", desc="加入等级，数字0到9999")
     */
    public function updateAction()
    {
        try {
            Tool::checkParam(['icon','desc','joinLevel'], $this->post);
            $userId = $this->user['id'];
            $icon = $this->post['icon'];
            $desc = $this->post['desc'];
            $joinLevel = $this->post['joinLevel'];
            // 查询这个工会信息
            $UnionObj = Union::instance()->findOne(['user_id'=>$userId], true);
            if(empty($UnionObj)){
                throw new MyException("数据不存在");
            }
            // 获取用户
            $postData = array(
                'id' => $UnionObj['id'],
                'icon' => $icon,
                'desc' => $desc,
                'join_level' => $joinLevel,
            );
            $UnionObj = Union::instance()->updateOne($postData);
            $this->setData($UnionObj);
            $this->sendJson();
        } catch (MyException $e) {
            echo $e->toJson();
        }
    }

    /**
     * @Apidoc\Title("工会-加入工会")
     * @Apidoc\Desc("1. 工会不存在不能加入工会  2. 已加入工会不能再次加入工会。 3. 工会人员超过最大限制不能加入工会  4. 用户等级不到工会等级不能加入工会")
     * @Apidoc\Method("POST")
     * @Apidoc\Param ("id", require=true, type="int", desc="工会id")
     */
    public function joinAction()
    {
        try {
            Tool::checkParam(['id'],$this->post);
            $userId = $this->user['id'];
            $userName = $this->user['name'];
            $id = $this->post['id'];
            if($this->user['union_id'] != 0){
                throw new MyException("您已加入工会,请勿重复加入工会");
            }
            // 查询这个工会信息
            $UnionObj = Union::instance()->findOne(['id'=>$id], true);
            if(empty($UnionObj)){
                throw new MyException("工会不存在或已解散");
            }
            // 工会人员超过最大限制不能加入工会
            if($UnionObj['member_max'] <= $UnionObj['member_now']){
                throw new MyException("工会已满,无法加入");
            }
            // 用户等级不到工会等级不能加入工会
            if($this->user['level'] < $UnionObj['join_level']){
                throw new MyException("未能达到工会要求等级,无法加入");
            }
            // 启动事务
            Db::startTrans();
            // 加入工会
            User::instance()->updateMore(['union_id' => $UnionObj['id']],['id' => $userId]);
            // 刷新工会成员数量
            Union::instance()->flushMember($UnionObj['id']);
            // 增加一个通知
            $postData = array(
                'user_id' => 0,
                'union_id' => $UnionObj['id'],
                'content' => $userName." 加入了公会",
                'created_at' => $this->time,
            );
            Talk::instance()->addOne($postData);
            Db::commit();
            $this->sendJson();
        } catch (MyException $e) {
            echo $e->toJson();
        }
    }

    /**
     * @Apidoc\Title("工会-退出")
     * @Apidoc\Desc("1. 工会成员退出工会就只退出工会. 2.创建工会的人退出工会，工会就解散了.  3. 工会解散后不可恢复")
     * @Apidoc\Method("POST")
     */
    public function outAction()
    {
        try {
            $userId = $this->user['id'];
            $userName = $this->user['name'];
            $union_id = $this->user['union_id'];
            if($union_id == 0){
                throw new MyException("未加入工会,无法退出");
            }

            // 启动事务
            Db::startTrans();
            // 退出工会
            $postData = array(
                'id' => $userId,
                'union_id' => 0
            );
            User::instance()->updateOne($postData);
            // 刷新工会成员数量
            Union::instance()->flushMember($union_id);
            // 增加一个通知
            $postData = array(
                'user_id' => 0,
                'union_id' => $union_id,
                'content' => $userName." 退出了公会",
                'created_at' => $this->time,
            );
            Talk::instance()->addOne($postData);

            // 查询这个工会信息
            $UnionObj = Union::instance()->findOne(['user_id'=>$userId], true);
            // 如果是会长退出工会，就找工会分数最高的人为工会会长
            if(!empty($UnionObj)){
                $where = array();
                $where['orderBy'] = "score desc";
                $where['limit'] = 1;
                $where[] = ['union_id','=', $union_id];
                $UserObj = User::instance()->findMore($where, true);
                if(!empty($UserObj)){
                    $newUnionManage = $UserObj[0]['id'];
                    $unionPostData = array(
                        'id' => $union_id,
                        'user_id' => $newUnionManage
                    );
                    Union::instance()->updateOne($unionPostData);
                }else{
                    // 工会一个人都没有了，删除工会数据
                    Union::instance()->delOne($union_id);
                }
            }
            Db::commit();
            $this->sendJson();
        } catch (MyException $e) {
            echo $e->toJson();
        }
    }

    /**
     * @Apidoc\Title("工会-踢人")
     * @Apidoc\Desc("1. 只有工会会长可以操作. 2. 会长不能被踢")
     * @Apidoc\Method("POST")
     * @Apidoc\Param ("userId", require=true, type="int", desc="用户id")
     */
    public function kickAction()
    {
        try {
            Tool::checkParam(['userId'],$this->post);
            $kickUserId = $this->post['userId'];
            $userId = $this->user['id'];
            $union_id = $this->user['union_id'];
            if($kickUserId == $userId){
                throw new MyException("不能自己踢自己");
            }
            // 查询这个工会信息
            $UnionObj = Union::instance()->findOne(['user_id'=>$userId], true);
            if(empty($UnionObj)){
                throw new MyException("您不是会长,不能操作");
            }else{
                // 查找被踢的人的用户信息
                $kickUserObj = User::instance()->findOne(['id'=>$kickUserId],true);
                if(empty($kickUserObj)){
                    throw new MyException("用户不存在");
                }
                if($kickUserObj['union_id'] != $union_id){
                    throw new MyException("被踢的用户不在您公会中,不能操作");
                }
                // 启动事务
                Db::startTrans();
                // 被踢的人
                $postData = array(
                    'id' => $kickUserObj['id'],
                    'union_id' => 0
                );
                User::instance()->updateOne($postData);
                // 刷新工会成员数量
                Union::instance()->flushMember($union_id);
                // 增加一个通知
                $postData = array(
                    'user_id' => 0,
                    'union_id' => $union_id,
                    'content' => $kickUserObj['name']." 退出了公会",
                    'created_at' => $this->time,
                );
                Talk::instance()->addOne($postData);
                Db::commit();
            }
            $this->sendJson();
        } catch (MyException $e) {
            echo $e->toJson();
        }
    }

    /**
     * @Apidoc\Title("工会-转让")
     * @Apidoc\Desc("1. 只有工会成员才能接受会长. 2. 原会长转让后变成普通成员")
     * @Apidoc\Method("POST")
     * @Apidoc\Param ("userId", require=true, type="int", desc="用户id")
     */
    public function transferAction()
    {
        try {
            Tool::checkParam(['userId'],$this->post);
            $kickUserId = $this->post['userId'];
            $userId = $this->user['id'];
            $union_id = $this->user['union_id'];
            // 查询这个工会信息
            $UnionObj = Union::instance()->findOne(['user_id'=>$userId], true);
            if(empty($UnionObj)){
                throw new MyException("您不是会长,不能操作");
            }else{
                // 查找被踢的人的用户信息
                $kickUserObj = User::instance()->findOne(['id'=>$kickUserId],true);
                if(empty($kickUserObj)){
                    throw new MyException("用户不存在");
                }
                if($kickUserObj['union_id'] != $union_id){
                    throw new MyException("转让会长的用户不是公会成员,不能操作");
                }
                // 被踢的人
                $postData = array(
                    'id' => $union_id,
                    'user_id' => $kickUserId
                );
                Union::instance()->updateOne($postData);
            }
            $this->sendJson();
        } catch (MyException $e) {
            echo $e->toJson();
        }
    }

    /**
     * @Apidoc\Title("工会-工会全部成员信息")
     * @Apidoc\Method("GET")
     * @Apidoc\Param ("id", require=true, type="int", desc="工会id")
     * @Apidoc\Returned("name", type="int", desc="昵称")
     * @Apidoc\Returned("gold", type="int", desc="金币")
     * @Apidoc\Returned("level", type="int", desc="通关级别")
     * @Apidoc\Returned("score", type="int", desc="分数，理论上通关级别=分数，为了后面扩展，所以用两个字段处理")
     * @Apidoc\Returned("score_season", type="int", desc="当前赛季分数")
     * @Apidoc\Returned("ip", type="int", desc="用户ip地址")
     * @Apidoc\Returned("nation", type="int", desc="用户所属国家，用来做本地排行榜")
     * @Apidoc\Returned("union_id", type="int", desc="工会id")
     * @Apidoc\Returned("created_at", type="int", desc="创建时间")
     */
    public function userListAction()
    {
        try {
            Tool::checkParam(['id'],$this->get);
            $id = $this->get['id'];
            // 查询这个工会信息
            $UnionObj = Union::instance()->findOne(['id'=>$id], true);
            if(empty($UnionObj)){
                throw new MyException("工会不存在");
            }

            $where['select'] = "id,name,level,score,score_season,help_num";
            $where['orderBy'] = "score desc";
            $where[] = ['union_id','=',$id];
            $userObjs = User::instance()->findMore($where);

            $this->setData(array(
                'unionInfo' => $UnionObj,
                'userList' => $userObjs
            ));
            $this->sendJson();
        } catch (MyException $e) {
            echo $e->toJson();
        }
    }

}
